package com.wnhz.work.yz.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.wnhz.work.yz.R;
import com.wnhz.work.yz.wheel.NumericWheelAdapter;
import com.wnhz.work.yz.wheel.OnWheelChangedListener;
import com.wnhz.work.yz.wheel.WheelView;

import java.util.Calendar;

/**
 * Created by admin on 2017/1/11.
 */
public class MyDatePicker3 {
    private static final String TAG = "MyDatePicker3";

    private Dialog dialog_time;
    private Context context;
    //	private boolean timeChanged = false;
//	private boolean timeScrolled = false;
    StringBuffer buffer;
    private String age;
    private int mCurYear;
    private int mCurMonth;

    private int mCurHour;
    private int mCurMinute;

    private String[] dateType;
    private TextView submit;
    private TextView cancel;
    private DateNumericAdapter monthAdapter, dayAdapter, yearAdapter, hourAdapter, minuteAdapter;
    private int mCurDay;
    private int style;

    /**
     * 判断时间先后顺序
     */
    private String startTimes;
    private String endTimes;
    private long startTime;
    private long endTime;
    private String initDateTime;


    public MyDatePicker3(Context context) {
        this.context = context;
        style = R.style.Dialog_Fullscreen;
        Calendar calendar = Calendar.getInstance();

//        initDateTime = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-"
//                + calendar.get(Calendar.DAY_OF_MONTH);
    }


    public MyDatePicker3(Context context, int style) {
        this.context = context;
        this.style = style;
    }

    /**
     * 选择日期对话框
     *
     * @param tv_time
     */

    public void selectDateDialog(final TextView tv_time, String defaultTime, final String tag) {
        View view = newDataDialog(R.layout.view_pixker_data2);

        submit = (TextView) view.findViewById(R.id.submit);
        cancel = (TextView) view.findViewById(R.id.cancel);
//        final WheelView year = (WheelView) view.findViewById(R.id.year);
//        final WheelView month = (WheelView) view.findViewById(R.id.month);
//        final WheelView day = (WheelView) view.findViewById(R.id.day);
        final WheelView hour1 = (WheelView) view.findViewById(R.id.hour1);
        final WheelView hour2 = (WheelView) view.findViewById(R.id.hour2);

//        year.setVisibleItems(7);
//        month.setVisibleItems(7);
//        day.setVisibleItems(7);
        hour1.setVisibleItems(7);
        hour2.setVisibleItems(7);

        try {
//            String time = ((TextView) tv_time).getText().toString().trim();
//            if (TextUtils.isEmpty(time)) {
            if (TextUtils.isEmpty(defaultTime)) {
                this.age = "2016-01-01";
            } else {
                this.age = defaultTime;
            }
//            } else {
//                this.age = time;
//            }
        } catch (Exception e) {
            // TODO: handle exception
            this.age = "2016-01-01";
        }


        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Log.i(TAG, "onClick: tag==" + tag + "\nstartTimes==" + startTimes
                        + "\nendTimes==" + endTimes + "\ninitDateTime==" + initDateTime);

                /**
                 * 弹出的是开始的时间
                 */
                if ("start".equals(tag)) {
                    //结束时间未填写，与当前时间判断
//                    if (null == endTimes || "".equals(endTimes)) {
//
//                        Long currentTime = changeStringTimesToLong(initDateTime);
//                        Long chooseTime = changeStringTimesToLong(age);
//                        //选择时间大于当前时间
//                        if (chooseTime > currentTime) {
////                            Toast.makeText(context, "开始日期不得大于当前日期", Toast.LENGTH_SHORT).show();
//                            MyToast("开始时间不得大于当前时间");
//                            return;
//                        }
//
//                    }
                    //结束时间填写了，与结束时间判断
//                    else {
//                        Long endTime = changeStringTimesToLong(endTimes);
                        Long endTime = Long.valueOf(endTimes);
//                        Long chooseTime = changeStringTimesToLong(age);
                        Long chooseTime = Long.valueOf(age);
                        //选择时间大于当前时间
                        if (chooseTime > endTime) {
//                            Toast.makeText(context, "开始日期不得大于结束日期", Toast.LENGTH_SHORT).show();
                            MyToast("开始时间不得大于当前时间");
                            return;
//                        }
                    }

                }
                /**
                 * 弹出的是结束的时间
                 */
                else if ("end".equals(tag)) {
                    //开始时间未填写，与当前时间判断
//                    if (null == startTimes || "".equals(startTimes)) {
//                        Long currentTime = changeStringTimesToLong(initDateTime);
//                        Long chooseTime = changeStringTimesToLong(age);
//                        //选择时间大于当前时间
//                        if (chooseTime > currentTime) {
////                            Toast.makeText(context, "结束日期不得大于当前日期", Toast.LENGTH_SHORT).show();
//                            MyToast("结束日期不得大于当前日期");
//                            return;
//                        }
//                    }
                    //开始时间填写了
//                    else {
//                        Long currentTime = changeStringTimesToLong(initDateTime);
//                    Long endTime = changeStringTimesToLong(endTimes);
                    Long endTime = Long.valueOf(endTimes);
//                        Long chooseTime = changeStringTimesToLong(age);
                    Long chooseTime = Long.valueOf(age);
                    //选择时间大于当前时间
                    if (chooseTime < chooseTime) {
//                            Toast.makeText(context, "结束日期不得小于开始日期", Toast.LENGTH_SHORT).show();
                        MyToast("结束时间不得大于开始时间");
                        return;
//                        } else if (chooseTime > currentTime) {
////                            Toast.makeText(context, "结束日期不得大于当前日期", Toast.LENGTH_SHORT).show();
//                            MyToast("结束日期不得大于当前日期");
//                            return;
//                        }
//                    }
                    }
                }


                ((TextView) tv_time).setText("" + age);
                dialog_time.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog_time.dismiss();
            }
        });
        Calendar calendar = Calendar.getInstance();
        OnWheelChangedListener listener = new OnWheelChangedListener() {
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                updateDays(hour1, hour2);

            }

        };
        /*int curYear = calendar.get(Calendar.YEAR);
        if (age != null && age.contains("-")) {
            String str[] = age.split("-");
            mCurYear = 100 - (curYear - Integer.parseInt(str[0]));
            mCurMonth = Integer.parseInt(str[1]) - 1;
            mCurDay = Integer.parseInt(str[2]) - 1;
        }
        dateType = context.getResources().getStringArray(R.array.date);*/
//        monthAdapter = new DateNumericAdapter(context, 1, 12, 5);
//        monthAdapter.setTextType(dateType[1]);
//        month.setViewAdapter(monthAdapter);
//        month.setCurrentItem(mCurMonth);
//        month.addChangingListener(listener);
        // year

//        yearAdapter = new DateNumericAdapter(context, curYear - 100, curYear + 100, curYear);
//        yearAdapter.setTextType(dateType[0]);
//        year.setViewAdapter(yearAdapter);
//        year.setCurrentItem(mCurYear);
//        year.addChangingListener(listener);
        // day
        dateType = context.getResources().getStringArray(R.array.date);
        hourAdapter = new DateNumericAdapter(context, 0, 23, 12);
        hourAdapter.setTextType(dateType[3]);
        hour1.setViewAdapter(hourAdapter);
        hour1.setCurrentItem(12);
        hour1.addChangingListener(listener);

        DateNumericAdapter hourAdapter2 = new DateNumericAdapter(context, 0, 23, 12);
        hourAdapter2.setTextType(dateType[3]);
        hour2.setViewAdapter(hourAdapter2);
        hour2.setCurrentItem(12);
        hour2.addChangingListener(listener);
/*
        updateDays(hour1, hour2);
//        day.setCurrentItem(mCurDay);
        updateDays(hour1, hour2);
//        day.addChangingListener(listener);*/

        dialog_time.show();
    }




    @SuppressWarnings("deprecation")
    private View newDataDialog(int layoutID) {
        buffer = new StringBuffer();
        dialog_time = new Dialog(context, style);
        dialog_time.requestWindowFeature(Window.FEATURE_NO_TITLE);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(layoutID, null);
        int screenWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();

        Window window = dialog_time.getWindow();
        // 重新设置
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setWindowAnimations(R.style.addresspickerstyle); // 添加动画
        window.setGravity(Gravity.BOTTOM);
        // window.setWindowAnimations(R.style.mystyle); // 添加动画
        lp.x = 0; // 新位置X坐标
        lp.y = 0; // 新位置Y坐标
        // lp.width = screenWidth;
        // window.setAttributes(lp);
        view.setMinimumWidth(screenWidth - 0);
        dialog_time.setContentView(view, lp);
        return view;
    }


    /**
     * 判断是否是闰年
     *
     * @param year
     * @return
     */
    private boolean isRunNian(int year) {
        if ((year % 4 == 0 && year % 100 != 0) | year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 年月日 的更新操作
     *
     * @param hour1
     * @param hour2
     */
    public void updateDays(WheelView hour1, WheelView hour2) {

        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + year.getCurrentItem());
//        calendar.set(Calendar.MONTH, month.getCurrentItem());
        calendar.set(Calendar.HOUR, hour1.getCurrentItem());
        calendar.set(Calendar.HOUR, hour2.getCurrentItem());

//        int currentYear = year.getCurrentItem();
        int currentYear = hour1.getCurrentItem();


        boolean isRunYear = isRunNian(currentYear);
//        calendar.set(Calendar.MONTH, month.getCurrentItem());
        calendar.set(Calendar.HOUR, hour2.getCurrentItem());

//        int currentMonth = month.getCurrentItem() + 1;
        int currentMonth = hour2.getCurrentItem() + 1;
        int maxDays = 31;

        switch (currentMonth) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                maxDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                maxDays = 30;
                break;
            case 2:
                if (isRunYear == true) {
                    maxDays = 29;
                } else {
                    maxDays = 28;
                }
                break;
            default:
                break;
        }

//        int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//        dayAdapter = new DateNumericAdapter(context, 1, maxDays, calendar.get(Calendar.DAY_OF_MONTH) - 1);
//        dayAdapter.setTextType(dateType[2]);
//        day.setViewAdapter(dayAdapter);
//        int curDay = Math.min(maxDays, day.getCurrentItem() + 1);
//        day.setCurrentItem(curDay - 1, true);
//        int years = calendar.get(Calendar.YEAR) - 100;
//        String monthss = "";
//        String dayss = "";
//        if (month.getCurrentItem() + 1 <= 9) {
//            monthss = "0" + (month.getCurrentItem() + 1);
//        } else {
//            monthss = "" + (month.getCurrentItem() + 1);
//        }
//        if (day.getCurrentItem() + 1 <= 9) {
//            dayss = "0" + (day.getCurrentItem() + 1);
//        } else {
//            dayss = "" + (day.getCurrentItem() + 1);
//        }
        int hours1 = hour1.getCurrentItem();
        int hours2 = hour2.getCurrentItem();

        age = hours1 + "至" + hours2;
    }

    /**
     * 时分的更新操作
     *
     * @param hour
     * @param minutes
     */
    public void updateTime(WheelView hour, WheelView minutes) {

		/*Calendar calendar = Calendar.getInstance();
        int maxMinute = calendar.getMaximum(Calendar.MINUTE);
		minuteAdapter = new DateNumericAdapter(context, 0, maxMinute, calendar.get(Calendar.MINUTE));
		minuteAdapter.setTextType(dateType[4]);
		minutes.setViewAdapter(minuteAdapter);
		int curDay = Math.min(maxMinute, minutes.getCurrentItem() + 1);
		minutes.setCurrentItem(curDay - 1, true);*/
        String hourss = "";
        String minutess = "";
        if (hour.getCurrentItem() <= 9) {
            hourss = "0" + (hour.getCurrentItem());
        } else {
            hourss = "" + (hour.getCurrentItem());
        }
        if (minutes.getCurrentItem() <= 9) {
            minutess = "0" + (minutes.getCurrentItem());
        } else {
            minutess = "" + (minutes.getCurrentItem());
        }

        age = hourss + ":" + minutess;
    }


    /**
     * Adapter for numeric wheels. Highlights the current value.
     */
    private class DateNumericAdapter extends NumericWheelAdapter {
        // Index of current item
        int currentItem;
        // Index of item to be highlighted
        int currentValue;

        /**
         * Constructor
         */
        public DateNumericAdapter(Context context, int minValue, int maxValue, int current) {
            super(context, minValue, maxValue);
            this.currentValue = current;
            setTextSize(20);
        }

        protected void configureTextView(TextView view) {
            super.configureTextView(view);
            view.setTypeface(Typeface.SANS_SERIF);
            view.setTextColor(0xff333333);
        }

        public CharSequence getItemText(int index) {
            currentItem = index;
            return super.getItemText(index);
        }

    }


    /**
     * 用于判断时间先后
     */

    public String getStartTimes() {
        return startTimes;
    }

    public void setStartTimes(String startTimes) {
        this.startTimes = startTimes;
    }

    public String getEndTimes() {
        return endTimes;
    }

    public void setEndTimes(String endTimes) {
        this.endTimes = endTimes;
    }


    private Toast toast;

    private void MyToast(String s) {
        if (toast == null)
            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
        else
            toast.setText(s);
        toast.show();
    }


}
